package com.caichen.scheduler.task;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.caichen.jpush.config.JPushConfig;
import com.caichen.jpush.handle.JPush;
import com.caichen.scheduler.enums.JPushClientCreator;
import com.caichen.scheduler.pojo.DelayedOrder;
import com.caichen.scheduler.service.OrderService;
import com.caichen.utils.encrypt.MD5;

/** 
 * @ClassName: DelayedOrderPushTask
 * @author: Czh 
 * @date 2017年8月23日 下午4:39:03 
 */
public class DelayedOrderPushTask {
	
	private static Logger logger = LoggerFactory.getLogger(DelayedOrderPushTask.class);
	
	@Resource
	private OrderService orderService;
	
	@Value("#{propertie['delayedOrder.day']}")
	private Integer day;
	
	@Value("#{propertie['apns.production']}")
	private String apnsProduction;
	
	private static JPush jpush;
	
	public void run() {
		logger.info("****************************************延迟订单推送定时任务开始****************************************");
		processJpushObject(apnsProduction);
		List<DelayedOrder> orders = orderService.findDelayedOrderList(day, 8);
		for (DelayedOrder order : orders) {
			StringBuilder sb=new StringBuilder();
			sb.append("温馨提示：亲爱的CC+VIP用户，您订单编号为").append(order.getOrderNo()).append("的“延迟支付”");
			if(order.getDays()!=null&&order.getDays()-day>3){
				sb.append("已经过期").append(order.getDays()-day-3).append("天了，请在“进货APP”进行相关操作，以免逾期，影响后续工作，非常感谢。【小C真诚为您服务】");
			}else{
				sb.append("还有").append(order.getDays()-day).append("天就到期了，请在“进货APP”进行相关操作，以免逾期，影响后续工作，非常感谢。【小C真诚为您服务】");
			}
			Map<String,String> extrasParam=new HashMap<>();
			extrasParam.put("type", "2");
			jpush.sendToAlias(MD5.encode(order.getMemberAccount()), "延迟支付订单", null, sb.toString(), extrasParam);
		}
		logger.info("****************************************延迟订单推送定时任务结束****************************************");
	}

	
	/**
	 * 创建jpush对象
	 */
	private void processJpushObject(String apnsProduction) {
		if (jpush == null) {
			synchronized (this) {
				if (jpush == null) {
					jpush = new JPush(JPushConfig.getClient(JPushClientCreator.CC_CLIENT.getAppkey(), JPushClientCreator.CC_CLIENT.getSecret()), 
							"false".equals(apnsProduction) ? false : true);
				} 
			}
		}
	}
}
